﻿using System;

namespace Inovout.NumberGenerator
{
    public class SequenceFunction:NumberFunction
    {
        public SequenceFunction()
            : this(new string[] { "1", "1", "6", 
                Guid.NewGuid().ToString("N"), ((int)SequencePeriod .NoPeriod).ToString()})
        {
        }
        public SequenceFunction(string[] arguments)
            : base("Sequence")
        {
            increment = int.Parse(arguments[0]);
            seed = int.Parse(arguments[1]);
            length = int.Parse(arguments[2]);
            key = arguments[3]; 
            period = (SequencePeriod)int.Parse(arguments[4]);
        }
        public override string[] Arguments
        {
            get { return new string[] {increment.ToString(),seed.ToString(),length.ToString(),key,((int)period).ToString() }; }
        }
        private int increment;
        public int Increment
        {
            get { return increment; }
            set { increment = value; }
        }
        private int seed;
        public int Seed
        {
            get { return seed; }
            set { seed = value; }
        }
        private int length;
        public int Length
        {
            get { return length; }
            set { length = value; }
        }
        private SequencePeriod period;
        public SequencePeriod Period
        {
            get { return period; }
            set { period = value; }
        }
        private string key;
        public string Key
        {
            get { return key; }
            set { key = value; }
        }
        public override string Build()
        {
            SequenceNumberRepository sequenceNumberRepository = ComponentRegistry.Resolve<SequenceNumberRepository>();
            int sequenceNumberPeriod;
            switch (Period)
            {
                case SequencePeriod.Year:
                    sequenceNumberPeriod = DateTime.Now.Year;
                    break;
                case SequencePeriod.Month:
                    sequenceNumberPeriod = int.Parse(DateTime.Now.ToString("yyyyM"));
                    break;
                case SequencePeriod.Day:
                    sequenceNumberPeriod = int.Parse(DateTime.Now.ToString("yyyyMd"));
                    break;
                default:
                    sequenceNumberPeriod = -1;
                    break;
            }
            int sequence = sequenceNumberRepository.Next(key, sequenceNumberPeriod, seed, increment);
            return (sequence + Seed).ToString("D" + length.ToString());
        }

    }
}
